import os import random import tkinter as tk from tkinter import messagebox from PIL import Image, ImageTk import pygame # For playing audio # Define the folders IMAGE_FOLDER = r"C:\Users\Admin\PycharmProjects\PythonProject1\Images\Animals" AUDIO_FOLDER = r"C:\Users\Admin\PycharmProjects\PythonProject1\Audio" # Ensure the folder exists if not os.path.exists(IMAGE_FOLDER): os.makedirs(IMAGE_FOLDER) # Create the folder if it doesn't exist print(f"Created folder: {IMAGE_FOLDER}. Please add some animal images.") # Get list of image files image_files = [f for f in os.listdir(IMAGE_FOLDER) if f.endswith(('.png', '.jpg', '.jpeg'))] # Ensure there are images before continuing if not image_files: print("No images found in the 'animals' folder. Please add some images and restart the script.") exit(1) # Mapping of filenames to animal names (assuming filenames are like 'lion.jpg') animal_names = {file: os.path.splitext(file)[0].capitalize() for file in image_files} random.shuffle(image_files) # Initialize Pygame for audio pygame.mixer.init() class AnimalQuizApp: def __init__(self, root): self.root = root self.root.title("Animal Quiz") self.score = 0 self.index = 0 self.attempted = False # Flag to track whether the user has already attempted the question # Frame for image and options self.main_frame = tk.Frame(self.root) self.main_frame.pack(pady=10) # Image frame self.image_frame = tk.Frame(self.main_frame) self.image_frame.pack(side=tk.LEFT, padx=20) self.image_label = tk.Label(self.image_frame) self.image_label.pack() # Options frame self.options_frame = tk.Frame(self.main_frame) self.options_frame.pack(side=tk.LEFT) self.buttons = [] for i in range(4): btn = tk.Button(self.options_frame, text="", font=("Arial", 14), width=20, command=lambda b=i: self.check_answer(b)) btn.pack(pady=5) self.buttons.append(btn) # Feedback label self.feedback_label = tk.Label(self.root, text="", font=("Arial", 14), fg="red") self.feedback_label.pack(pady=10) self.load_question() def load_question(self): if self.index >= len(image_files): messagebox.showinfo("Quiz Complete", f"Your final score is {self.score}/{len(image_files)}") self.root.quit() return file = image_files[self.index] self.correct_answer = animal_names[file] img_path = os.path.join(IMAGE_FOLDER, file) img = Image.open(img_path) img = img.resize((600, 600)) self.photo = ImageTk.PhotoImage(img) self.image_label.config(image=self.photo) # Get random choices, ensuring the correct answer is included num_choices = min(4, len(animal_names)) # If only 2-3 images exist, don't pick 4 choices = [self.correct_answer] # Start by adding the correct answer # Get additional random choices, ensuring no duplicates remaining_choices = list(animal_names.values()) remaining_choices.remove(self.correct_answer) choices.extend(random.sample(remaining_choices, num_choices - 1)) random.shuffle(choices) # Shuffle the choices to randomize their order # Make sure we are not trying to assign more choices than we have buttons for i, choice in enumerate(choices): if i < len(self.buttons): self.buttons[i].config(text=choice, state=tk.NORMAL) # Enable only the needed buttons # Disable unused buttons if fewer than 4 choices for i in range(len(choices), len(self.buttons)): self.buttons[i].config(text="", state=tk.DISABLED) self.correct_index = choices.index(self.correct_answer) # Reset the attempt flag for the new question self.attempted = False def check_answer(self, chosen_index): # If the user selects the correct answer if self.buttons[chosen_index]["text"] == self.correct_answer: self.score += 1 self.play_audio("Rightanswer.mp3") self.feedback_label.config(text="Correct! Well done!", fg="green") self.index += 1 # Move to next question self.load_question() self.attempted = False # Reset the attempt flag else: # If the answer is wrong, but they haven't tried yet if not self.attempted: # Play the retry audio and give them a second chance self.play_audio("Wronganswertryagain.mp3") self.feedback_label.config(text="Wrong! Try again!", fg="red") self.attempted = True # Set the flag to prevent further retries self.disable_buttons() # Disable buttons for a moment to show feedback # Re-enable the buttons after 2 seconds for retry self.root.after(2000, self.enable_buttons) else: # If the user already attempted once, play the audio for second wrong answer self.play_audio("Wrongansweragainletstryanotherquestion.mp3") self.feedback_label.config(text=f"The correct answer was {self.correct_answer}.", fg="red") # Move to the next question after a short delay self.root.after(2000, self.next_question) def next_question(self): """Move to the next question after showing the feedback for a wrong attempt.""" self.index += 1 self.load_question() def disable_buttons(self): """Disable the answer buttons temporarily.""" for button in self.buttons: button.config(state=tk.DISABLED) def enable_buttons(self): """Re-enable the buttons for retry.""" for button in self.buttons: button.config(state=tk.NORMAL) def play_audio(self, filename): """Play an audio file from the Audio folder.""" audio_path = os.path.join(AUDIO_FOLDER, filename) if os.path.exists(audio_path): pygame.mixer.music.load(audio_path) pygame.mixer.music.play() else: print(f"Audio file not found: {audio_path}") if __name__ == "__main__": root = tk.Tk() app = AnimalQuizApp(root) root.mainloop()